package ar.com.age.distribuidora.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ar.com.age.distribuidora.dao.ClienteDao;
import ar.com.age.distribuidora.dominio.Cliente;

@Component
public class ClienteHibernateDao implements ClienteDao {

	private SessionFactory sessionFactory;

	@Autowired(required = true)
	public void setSessionFactory(SessionFactory factory) {
		this.sessionFactory = factory;
	}

	private Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}
	
	@Override
	public Cliente saveOrUpdate(Cliente cliente) {
		if (cliente.getId() == null) {
			getCurrentSession().save(cliente);
		} else {
			getCurrentSession().update(cliente);
		}
		return cliente;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Cliente> getAll() {
		Query query = getCurrentSession().createQuery(
				"from " + Cliente.class.getName());
		return query.list();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Cliente> find(String codigo, String apellido, String nombre, String cuit, String razonSocial, String estado){
		
		List<Cliente> clientes = null;
		Criteria criteria = getCurrentSession().createCriteria(Cliente.class);
		
		if(codigo != "")
			criteria.add(Restrictions.like("codigo", "%"+codigo+"%"));
		if(apellido != "")
			criteria.add(Restrictions.like("apellido", "%"+apellido+"%"));
		if(nombre != "")
			criteria.add(Restrictions.like("nombre", "%"+nombre+"%"));
		if(cuit != "")
			criteria.add(Restrictions.like("cuit", "%"+cuit+"%"));
		if(razonSocial != "")
			criteria.add(Restrictions.like("razonSocial", "%"+razonSocial+"%"));
		if(estado != "")
			criteria.add(Restrictions.like("estado", "%"+estado+"%"));
		
		clientes = criteria.list();
		
		return clientes;
	}
	
	@Override
	public void physicalDelete(Cliente cliente){
		
		getCurrentSession().delete(cliente);
				
	}
}
